﻿using Castle.DynamicProxy;
using CNKI.TPI.Web.Admin.IBLL;
using CNKI.TPI.Web.Admin.IDAO;
using CNKI.TPI.Web.Admin.Model;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CNKI.TPI.Web.UI.Controllers.Admin
{
    public class Admin_UserController : BaseController
    {
        //
        // GET: /Admin_User/

        IUserMgmtService userMService = null;
        ISingleDBPublishService singleService = null;
        INaviService naviService = null;

        public Admin_UserController(IUserMgmtService userMService, ISingleDBPublishService singleService, IUserService userService,  INaviService naviService = null)
        {
            this.userMService = generator.CreateInterfaceProxyWithTarget<IUserMgmtService>(userMService, new IInterceptor[] { new LogInterceptor() });
            this.singleService = generator.CreateInterfaceProxyWithTarget<ISingleDBPublishService>(singleService, new IInterceptor[] { new LogInterceptor() });
            this.naviService = generator.CreateInterfaceProxyWithTarget<INaviService>(naviService, new IInterceptor[] { new LogInterceptor() });

        }
        /// <summary>
        /// 用户管理 
        /// <returns></returns>
        public ActionResult UserIndex()
        {
            IList<SYS_CMS_GROUP> list = userMService.GetGroup();
            if (list != null && list.Count > 0)
            {
                ViewBag.UserGroupList = list;
            }  //用户组下拉列表
            return View();
        }
        /// <summary>
        /// 用户组管理
        /// </summary>
        /// <returns></returns>
        public ActionResult GroupIndex()
        {
            return View();
        }
        /// <summary>
        /// 密级管理
        /// </summary>
        /// <returns></returns>
        public ActionResult SecurityIndex()
        {
            IList<SYS_CMS_SECURITY> list = userMService.GetSecurity();
            if (list != null && list.Count > 0)
            {
                ViewBag.SecurityList = list;
            }

            return View();
        }
        public ActionResult UnitIndex()
        {
            return View();
        }
        /// <summary>
        /// 用户单位管理查询
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult UnitSearch(string unitname, int pageIndexNow)
        {
            int pageSize = 10;//每页显示记录数
            int count = 0;//总条数
            IList<SYS_CMS_USER_UNIT> list = userMService.GetUnitPageSize(unitname, pageIndexNow, pageSize, out count);
            pagelistUnit(list, pageIndexNow, pageSize, count);
            return PartialView("UnitResult");
        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pageIndexNow"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        private void pagelistUnit(IList<SYS_CMS_USER_UNIT> list, int pageIndexNow, int pageSize, int count)
        {
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            if (list != null && list.Count > 0)
            {
                ViewBag.CompanyList = list;
            }
            sumPage = count / pageSize; //一共多少页
            if (count % pageSize != 0)
            {
                sumPage = sumPage + 1;
            }
            ColumnAliasHelper com = new ColumnAliasHelper();
            ViewBag.TotalPage = sumPage;
            ViewBag.PageList = com.GetPageList(pageIndexNow, sumPage, disPgae);
            ViewBag.PageNow = pageIndexNow;//当前页
            ViewBag.PageSize = pageSize;
            ViewBag.Count = count;
        }
       
        /// <summary>
        /// 部门管理
        /// </summary>
        /// <param name="unitid"></param>
        /// <returns></returns>
        public ActionResult DeptManager(int unitid)
        {
            IList<SYS_CMS_USER_UNIT_DEPT> DeptList = userMService.GetDeptByUnitID(unitid).OrderBy(c => c.SYSCODE).ToList();
            ViewBag.DeptList = DeptList;
            ViewBag.UnitID = unitid;
            //操作权限

            return PartialView("DeptManager");
        }
          /// <summary>
        /// 数据库权限列表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="flage"></param>
        /// <param name="pageIndexNow"></param>
        /// <returns></returns>
        public ActionResult DBAuthList(int id, int flage)
        {
            ViewBag.GroupUserID = id;
            ViewBag.Flage = flage;
            return PartialView("DBAuthList");
        }
        /// <summary>
        /// 数据库权限列表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="flage"></param>
        /// <param name="pageIndexNow"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult DBAuthResult(string id, int flage, int pageIndexNow,string dbname)
        {
            int pageSize = 10;//每页显示记录数  
            int sumCount = 0;//总条数
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            DataSet ds = new DataSet();
            ds = userMService.GetDBRightList(id, pageIndexNow, pageSize, (RightType)flage, dbname, new List<SearchType>() { SearchType.TPI });
            if (ds.Tables.Count > 0)
            {
                ViewBag.SearchResult = ds.Tables[0];
                if (ds.Tables[1].Rows.Count > 0)
                {
                    sumCount = int.Parse(ds.Tables[1].Rows[0]["TotalCount"].ToString());//总条数
                }
                sumPage = sumCount / pageSize; //一共多少页
                if (sumCount % pageSize != 0)
                {
                    sumPage = sumPage + 1;
                }
                ViewBag.TotalPage = sumPage;
                ColumnAliasHelper stringobj = new ColumnAliasHelper();
                ViewBag.PageList = stringobj.GetPageList(pageIndexNow, sumPage, disPgae);
                ViewBag.PageNow = pageIndexNow;//当前页
                ViewBag.PageSize = pageSize;
                ViewBag.ResultCount = sumCount;
            }
            return PartialView("DBAuthResult");
        }
        /// <summary>
        /// 保存数据库权限
        /// </summary>
        /// <param name="authdblist"></param>
        /// <param name="fieldlist"></param>
        /// <param name="daycount"></param>
        /// <param name="maxcount"></param>
        /// <param name="dbid">数据库ID</param>
        /// <param name="id">flage 为0id为用户ID，flage为1则是数据库ID</param>
        /// <param name="flage"></param>
        /// <returns></returns>
        public bool AuthSave(string authdblist, string fieldlist, int daycount, int maxcount, int dbid, int id, int flage,string navstr)
        {
            navstr = navstr.TrimEnd(';');
            return userMService.AuthSaveUser(authdblist, fieldlist, daycount, maxcount, dbid, id, (RightType)flage, navstr);
        }
        /// <summary>
        /// 保存所有库的所有权限
        /// </summary>
        /// <param name="id"></param>
        /// <param name="flage"></param>
        /// <returns></returns>
        public bool AllAuth(int id, int flage)
        {
            //flage0//用户权限 // 1用户组权限
            return userMService.AddAllDBRight(id, (RightType)flage);
        }
        /// <summary>
        /// 保存当前选择库的权限
        /// </summary>
        /// <param name="id"></param>
        /// <param name="dbid"></param>
        /// <param name="flage"></param>
        /// <returns></returns>
        public bool ThisAuth(int id, string dbid, int flage)
        {
            IList<string> idstr = dbid.Split(',');
            IList<int> idint = new List<int>();
            foreach (string item in idstr)
            {
                idint.Add(int.Parse(item));
            }
            return userMService.AddDBRight(id, idint, (RightType)flage);

        }

        /// <summary>
        /// 数据库权限编辑
        /// </summary>
        /// <param name="dbid"></param>
        /// <param name="id"></param>
        /// <param name="flage"></param>
        /// <returns></returns>
        public ActionResult DBAuthManager(int dbid, int id, int flage)
        {
            //根据dbcode获取该库的字段
            string dbcode = "";
            string dbname="";
            SYS_CMS_DATABASE listdb = singleService.GetDatabaseByID(dbid);
            if(listdb!=null)
            {
                dbcode = listdb.DatabaseCode;
                dbname=listdb.DatabaseName;
            }
            ViewBag.DBFieldList = singleService.GetDBField(dbcode);
            ViewBag.GroupUserID = id;
            ViewBag.Flage = flage;
            ViewBag.DBID = dbid;
            ViewBag.DbCode = dbcode;
            ViewBag.DbName = dbname;
            SYS_CMS_USER_ACL_DB_RIGHT obj = userMService.GetDBRight(id, dbid, (RightType)flage);
            DataTable dt = userMService.GetDBCLS(id, dbid, dbcode, (RightType)flage);
            ViewBag.CLSInfo = dt;
            if (obj != null)
            {
                ViewBag.DBRight = SessionHelper.PaserDBRight(obj.RightValue);
                ViewBag.DayCount = obj.DownloadCountOfDay;
                ViewBag.MaxCount = obj.MaxDownloadCount;
                ViewBag.FieldList = obj.RightFieldName;
                ViewBag.NavValue = obj.RightClsValue;
            }
            return PartialView("DBAuthManager");
        }
        /// <summary>
        /// 用户查询
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Search()
        {
            int pageIndexNow = 1;// 当前页    
            string username = "";
            if (!String.IsNullOrEmpty(Request["pageIndexNow"]))
            {
                pageIndexNow = int.Parse(Request["pageIndexNow"]);
            }
            if (!String.IsNullOrEmpty(Request["hiddenname"]))
            {
                username = Request["hiddenname"].ToString();
            }
            int pageSize = 10;//每页显示记录数

            int count = 0;//总条数
            IList<SYS_CMS_USER> list = userMService.GetUserByName(username, pageIndexNow, pageSize, out count);
            pagelist(list, pageIndexNow, pageSize, count);
            return PartialView("ResultList");

        }

        /// <summary>
        /// 根据用户组用户查询
        /// </summary>
        /// <param name="groupvalue"></param>
        /// <param name="pageIndexNow"></param>
        /// <returns></returns>
        public ActionResult GetListByGroupName(int groupvalue, int pageIndexNow)
        {
            int pageSize = 10;//每页显示记录数
            int count = 0;//总条数
            IList<SYS_CMS_USER> list = userMService.GetUserByGroupID(groupvalue, pageIndexNow, pageSize, out count);
            pagelist(list, pageIndexNow, pageSize, count);
            return PartialView("ResultList");

        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pageIndexNow"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        private void pagelist(IList<SYS_CMS_USER> list, int pageIndexNow, int pageSize, int count)
        {
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            if (list != null && list.Count > 0)
            {
                ViewBag.UserList = list;
            }
            sumPage = count / pageSize; //一共多少页
            if (count % pageSize != 0)
            {
                sumPage = sumPage + 1;
            }
            ColumnAliasHelper com = new ColumnAliasHelper();
            ViewBag.TotalPage = sumPage;
            ViewBag.PageList = com.GetPageList(pageIndexNow, sumPage, disPgae);
            ViewBag.PageNow = pageIndexNow;//当前页
            ViewBag.PageSize = pageSize;
            ViewBag.Count = count;
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        public ActionResult UserManager()
        {
            ViewBag.UserGroup = userMService.GetGroup();
            //ViewBag.UserGroupIp = userMService.GetGroupIpByUserID(1);
            ViewBag.Security = userMService.GetSecurity();
            ViewBag.UserUnit = userMService.GetUnit();

            ViewBag.thisUserID = 0;
            return PartialView("UserManager");
        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <returns></returns>
        public ActionResult UserModify(int userid)
        {
            ViewBag.thisUserID = userid;
            ViewBag.User = userMService.GetUserInfoByID(userid);//用户

            ViewBag.UserGroup = userMService.GetGroup(); //所有用户组
            //该用户对应的用户组
            ViewBag.UserGroupID = userMService.GetUserGroupID(userid);

            ViewBag.UserGroupIp = userMService.GetGroupIpByUserID(userid); //用户IP

            ViewBag.Security = userMService.GetSecurity();
            ViewBag.UserUnit = userMService.GetUnit();
            return PartialView("UserManager");
        }
        /// <summary>
        /// 根据单位获取部门
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public JsonResult GetDeptByUnit(int uid)
        {
            var res = new JsonResult();
            IList<SYS_CMS_USER_UNIT_DEPT> list = userMService.GetDeptByUnitID(uid);
            if (list != null && list.Count > 0)
            {
                res.Data = list;
            }
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。  
            return res;
        }
        /// <summary>
        /// 判读用户名是否存在
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public int IsExitUser(string username)
        {
            return userMService.IsExitUser(username);
        }
        /// <summary>
        /// 根据用户ID，删除用户
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool delUser(string idlist)
        {
            return userMService.DeleteUser(idlist);
        }
        /// <summary>
        /// 保存用户相关信息
        /// </summary>
        /// <param name="userobj"></param>
        /// <param name="grouplist"></param>
        /// <param name="iplist"></param>
        /// <param name="Flage"></param>
        /// <returns></returns>
        public int SaveUserInfo(SYS_CMS_USER userobj, IList<SYS_CMS_USER_GROUP> grouplist, IList<SYS_CMS_USER_IP> iplist)
        {
            return userMService.SaveUserInfo(userobj, grouplist, iplist);
        }
        /// <summary>
        /// 删除用户组
        /// </summary>
        /// <param name="idlist"></param>
        /// <returns></returns>
        public bool DelUserGroup(string idlist)
        {
            return userMService.DeleteUserGroup(idlist);
        }
        /// <summary>
        /// 保存用户组
        /// </summary>
        /// <param name="idlist"></param>
        /// <returns></returns>
        public bool SaveUserGroup(SYS_CMS_GROUP obj, IList<SYS_CMS_USER_IP> iplist)
        {
            return userMService.SaveGroup(obj, iplist);
        }
        /// <summary>
        /// 判读用户组是否存在
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public int IsExitUserGroup(string name, int sysid)
        {
            return userMService.IsExitUserGroup(name, sysid);
        }

        /// <summary>
        /// 删除密级
        /// </summary>
        /// <param name="idlist"></param>
        /// <returns></returns>
        public bool DelSecurity(string idlist)
        {
            return userMService.DeleteSecurity(idlist);
        }
        /// <summary>
        /// 判读用户组是否存在
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public int IsExitSecurity(string name, string value, int sysid)
        {
            return userMService.IsExitSecurity(name, value, sysid);
        }
        /// <summary>
        /// 保存密级
        /// </summary>
        /// <param name="idlist"></param>
        /// <returns></returns>
        public bool SaveSecurity(SYS_CMS_SECURITY obj)
        {
            return userMService.SaveSecurity(obj);
        }
        /// <summary>
        /// 保存用户单位
        /// </summary>
        /// <param name="unitobj"></param>
        /// <returns></returns>
        public bool SaveUnitInfo(SYS_CMS_USER_UNIT unitobj)
        {
            return userMService.SaveUnitInfo(unitobj);
        }
        /// <summary>
        /// 删除用户单位
        /// </summary>
        /// <param name="idlist"></param>
        /// <returns></returns>
        public bool DelUnit(string idlist)
        {
            return userMService.DeleteUnit(idlist);
        }
        /// <summary>
        ///判断单位名称是否重复
        /// </summary>
        /// <param name="name"></param>
        /// <param name="sysid"></param>
        /// <returns></returns>
        public int IsExitUnit(string name, int sysid)
        {
            return userMService.IsExitUnit(name, sysid);
        }


        public JsonResult GetDeptCodeChilds(string codegrde, int unitid)
        {
            string[] array = codegrde.Split(',');
            string code = array[0];
            int grade = int.Parse(array[1]) + 1;

            IList<SYS_CMS_USER_UNIT_DEPT> DeptList = userMService.GetDept(unitid, grade, code);
            var res = new JsonResult();
            res.Data = DeptList;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。 
            return res;

        }
        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="sysid"></param>
        /// <returns></returns>
        public bool DeleteDept(string codegradeid, int unitid)
        {
            string[] array = codegradeid.Split(',');
            string id = array[2];
            string code = array[0];
            return userMService.DeleteDept(id, code, unitid);
        }
        /// <summary>
        /// 保存部门
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SaveDeptInfo(int unitid, int sysid, string deptName, string parentcode, int grade)
        {
            int nextgrade = grade + 1;
            return userMService.SaveDeptInfo(unitid, sysid, deptName, parentcode, nextgrade);
        }



        public string GetCategoryInfo(string DbCode, int catid, int dbID)
        {
            StringBuilder treeContent = new StringBuilder();
            IList<CLS_NODE> categoryList = naviService.GetCategoryAllList(DbCode, catid, dbID);
            if (categoryList != null && categoryList.Count > 0)
            {
                treeContent.Append("<tree id=\"0\">");
                int preFlag = 0;
                foreach (CLS_NODE obj in categoryList)
                {
                    if (obj.Grade < preFlag)
                    {
                        for (var j = 0; j < preFlag - obj.Grade; j++)
                        {
                            treeContent.Append("</item>");
                        }
                    }
                    preFlag = obj.Grade;
                    treeContent.Append("<item  id=\"" + StringHelper.strXmlEncode(obj.Code) + "\" text=\"" + StringHelper.strXmlEncode(obj.Name) + "\">");
                    if (1 != obj.ChildFlag)
                    {
                        treeContent.Append("</item>");
                    }
                }
                for (var i = 0; i < preFlag - 1; i++)
                {     
                    treeContent.Append("</item>");
                }
                treeContent.Append("</tree>");
            }
          
            return treeContent.ToString();
       
        }
        /// <summary>
        /// 用户组查询
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult GroupSearch(string groupname,int pageIndexNow)
        {
            int pageSize = 10;//每页显示记录数
            int count = 0;//总条数
            IList<SYS_CMS_GROUP> list = userMService.GetGroupByName(groupname, pageIndexNow, pageSize, out count);
            pagelistGroup(list, pageIndexNow, pageSize, count);
            return PartialView("GroupResult");

        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pageIndexNow"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        private void pagelistGroup(IList<SYS_CMS_GROUP> list, int pageIndexNow, int pageSize, int count)
        {
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            if (list != null && list.Count > 0)
            {
                ViewBag.GroupList = list;
            }
            sumPage = count / pageSize; //一共多少页
            if (count % pageSize != 0)
            {
                sumPage = sumPage + 1;
            }
            ColumnAliasHelper com = new ColumnAliasHelper();
            ViewBag.TotalPage = sumPage;
            ViewBag.PageList = com.GetPageList(pageIndexNow, sumPage, disPgae);
            ViewBag.PageNow = pageIndexNow;//当前页
            ViewBag.PageSize = pageSize;
            ViewBag.Count = count;
        }

        /// <summary>
        /// 获取用户组IP
        /// </summary>
        /// <param name="dbcode"></param>
        /// <returns></returns>
        public JsonResult GetGroupIpList(int groupid)
        {
            var res = new JsonResult();
            IList<SYS_CMS_USER_IP> list = userMService.GetGroupIpByGroupID(groupid);
            if (list != null && list.Count > 0)
            {
                res.Data = list;
            }
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。  
            return res;
        }
    }
}
